#include "systemmanager.h"
#include "ui_systemmanager.h"
#include <QStandardItemModel>
#include <QDateTime>
#include <QFileDialog>
#include "../MainProject/loggermanager.h"

SystemManager::SystemManager(QWidget *parent) :
    QMainWindow(parent),
    ui(new Ui::SystemManager),
    logModel(new LogModel(this)),
    common(this)
{
    ui->setupUi(this);
    Logger().init();
    common.loadQssfromfile(":/qss/systemManegerQSS.qss");
    // 查找 UI 中的控件
    settingsButton = findChild<QPushButton*>("settingsButton");
    queryButton = findChild<QPushButton*>("queryButton");
    exportButton = findChild<QPushButton*>("exportButton");
    logsTableView = findChild<QTableView*>("logsTableView");
    startDateEdit = findChild<QDateEdit*>("startDateEdit");
    endDateEdit = findChild<QDateEdit*>("endDateEdit");
    logTypeComboBox = findChild<QComboBox*>("logTypeComboBox");

    // 连接按钮点击信号与槽函数
    connect(queryButton, &QPushButton::clicked, this, &SystemManager::onQueryButtonClicked);
    connect(exportButton, &QPushButton::clicked, this, &SystemManager::onExportButtonClicked);
    // connect(ui->logBtn, &QPushButton::clicked, this, &SystemManager::onQueryButtonClicked);
    // connect(ui->settingsButton, &QPushButton::clicked, this, &SystemManager::onExportButtonClicked);
    // 设置日期控件的默认值
    startDateEdit->setDate(QDate(2024, 6, 1));
    endDateEdit->setDate(QDate(2024, 7, 1));

    Logger().logInfo("SystemManager 已初始化。");
}

SystemManager::~SystemManager()
{
    delete ui;
}

// 查询按钮点击处理函数
void SystemManager::onQueryButtonClicked()
{
    QString startTime = startDateEdit->date().toString("yyyyMMdd") + "_000000";
    QString endTime = endDateEdit->date().toString("yyyyMMdd") + "_235959";
    QString logType = logTypeComboBox->currentText();

    Logger().logInfo(QString("查询从 %1 到 %2 的日志，类型为 %3").arg(startTime).arg(endTime).arg(logType));
    Logger().logOperation("用户点击了查询按钮");

    try {
        QJsonArray logs = logModel->readLogsFromFiles(
            logModel->queryLogTimestamps(),
            startTime,
            endTime,
            logType
            );
        displayLogs(logs);
    } catch (const std::exception &e) {
        Logger().logError(QString("查询日志时发生异常：%1").arg(e.what()));
    } catch (...) {
        Logger().logError("查询日志时发生未知异常。");
    }
}

// 显示日志的函数
void SystemManager::displayLogs(const QJsonArray& logs)
{
    QStandardItemModel *model = new QStandardItemModel(this);
    model->setHorizontalHeaderLabels(QStringList() << "时间戳" << "日志内容");

    // 遍历日志数组，填充模型
    for (const QJsonValue &value : logs) {
        QJsonObject record = value.toObject();
        QList<QStandardItem *> items;
        items.append(new QStandardItem(record.value("timestamp").toString()));
        items.append(new QStandardItem(record.value("log").toString()));
        model->appendRow(items);
    }

    logsTableView->setModel(model);

    // 设置表格列宽
    int totalWidth = logsTableView->viewport()->width();
    logsTableView->setColumnWidth(0, totalWidth * 2 / 10);
    logsTableView->setColumnWidth(1, totalWidth * 8 / 10);
}

// 导出按钮点击处理函数
void SystemManager::onExportButtonClicked()
{
    QString filePath = QFileDialog::getSaveFileName(this, "导出日志", "", "CSV Files (*.csv);;All Files (*)");
    if (!filePath.isEmpty()) {
        Logger().logOperation("用户点击了导出按钮");
        try {
            QJsonArray logs = logModel->readLogsFromFiles(
                logModel->queryLogTimestamps(),
                startDateEdit->date().toString("yyyyMMdd") + "_000000",
                endDateEdit->date().toString("yyyyMMdd") + "_235959",
                logTypeComboBox->currentText()
                );
            logModel->exportLogsToCSV(logs, filePath);
        } catch (const std::exception &e) {
            Logger().logError(QString("导出日志时发生异常：%1").arg(e.what()));
        } catch (...) {
            Logger().logError("导出日志时发生未知异常。");
        }
    }
}

void SystemManager::on_settingsButton_clicked()
{

}


void SystemManager::on_logBtn_clicked()
{

}

